import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login.vue'
import Home from '../views/Home.vue'
import Welcome from '../views/Welcome.vue'
import User from '../views/users/index.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    component: Login
  },
  {
    path: '/home',
    redirect: '/welcome',
    component: Home,
    children: [{
      path: '/welcome',
      component: Welcome
    }, {
      path: '/users',
      component: User
    }]
  }
]

const router = new VueRouter({
  routes
})
// 全局路由守卫，访问所有的路由之前会调用
router.beforeEach((to, from, next) => {
  const token = sessionStorage.getItem('token')
  // 有token代表登陆
  if (token) {
    next()
  } else {
    // 没有登陆 还要判断是否访问的是登录页面
    if (to.path === '/login') return next()
    next('/login')
  }
})
export default router
